package com.JavaWeb.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.JavaWeb.pojo.Role;
import com.JavaWeb.pojo.User;
import com.JavaWeb.service.role.RoleService;
import com.JavaWeb.service.role.RoleServiceImpl;
import com.JavaWeb.service.user.UserService;
import com.JavaWeb.service.user.UserServiceImpl;
import com.JavaWeb.util.Constants;
import com.JavaWeb.util.PageSupport;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//实现Servlet的复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");//获取前端传进来的值
//        拿传进来的参数进行判断，判断调用哪个方法
        if (method!=null&&method.equals("savepwd")){//判断获取的值是否是为savepwd，true就调用updatePwd方法
            this.updatePwd(req,resp);
        }
        else if(method!=null&&method.equals("pwdmodify")){
            this.pwdModify(req,resp);
        }
        else if (method!=null&&method.equals("query")){
            try {
                this.query(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else if (method!=null&&method.equals("add")){
            this.add(req,resp);
        }else if(method != null && method.equals("getrolelist")){
            try {
                this.getRoleList(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(method != null && method.equals("ucexist")) {
            this.userCodeExist(req, resp);
        }
        else if(method != null && method.equals("deluser")){
            this.delUser(req, resp);
        }
        else if(method != null && method.equals("view")){
            this.getUserById(req, resp,"userview.jsp");
        }
        else if(method != null && method.equals("modify")){
            this.getUserById(req, resp,"usermodify.jsp");
        }else if(method != null && method.equals("modifyexe")){
            this.modify(req, resp);
        }
        }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);

    }

    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        //从Session里拿到ID
        Object SessionID = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        boolean flag=false;

        if (SessionID!=null&& !StringUtils.isNullOrEmpty(newpassword)){
            UserServiceImpl userService = new UserServiceImpl();
            flag=userService.updatePwd(((User)SessionID).getId(),newpassword);
            if (flag){
                req.setAttribute("message","密码修改成功，请退出重新登录");
                //密码修改成功，移除当前Session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message","密码修改失败");
            }

        }else {
            req.setAttribute("message","新密码有问题");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //验证旧密码,Session中用用户密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从Session里拿到ID
        Object SessionID = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //Map:结果集
        HashMap<String, String> resultMap = new HashMap<String, String>();

        if (SessionID==null){//Session 失效了，过期了
            resultMap.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){//输入密码为空
            resultMap.put("result","error");
        }else {
            String userPassword = ((User) SessionID).getUserPassword();//旧密码
            if (oldpassword.equals(userPassword)){//传进来的密码和旧密码进行判断
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //JSONArray json工具类，转换格式
            /*
            * resultMap=["result","sessionerror","result","error"]
            * json格式=｛KEY:value｝*/
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();//刷新
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //用户管理
    public void query(HttpServletRequest req, HttpServletResponse resp) throws Exception {

////        查询用户列表
//
////        从前端获取数据
//        String queryUserName = req.getParameter("queryname");
//        String temp = req.getParameter("queryUserRole");
//        String pageIndex = req.getParameter("pageIndex");
//        int queryUserRole=0;
//
//        //获取用户列表
//        UserServiceImpl userService = new UserServiceImpl();
//
//        //第一次走这个请求。一定是第一页
//        int pagesize=5;
//        int currentpageNo=1;
//        if (queryUserName!=null){
//            queryUserName="";
//        }
//        if (temp!=null&&temp.equals("")){
//            queryUserRole=Integer.parseInt(temp);
//        }
//        if (pageIndex!=null){
//            currentpageNo=Integer.parseInt(pageIndex);
//        }
//        //获取用户总数(分页 上一页  下一页)
//        int totaCount = userService.getUserCount(queryUserName, queryUserRole);
////        总页数的支持
//        PageSupport pageSupport = new PageSupport();
//        pageSupport.setCurrentPageNo(currentpageNo);
//        pageSupport.setPageSize(pagesize);
//        pageSupport.setTotalCount(totaCount);
//
//
//       int totalCount = pageSupport.getTotalPageCount();//最大页数
////        int totaIPageCount=(int)(totaCount/pagesize);
//
//        //控制首页和页尾
//        //如果页面要小于1，就显示第一页
//        if (currentpageNo<1){
//            currentpageNo=1;
//        }
//        else if (currentpageNo>totalCount){//当前页大于最后一页
//            currentpageNo=totalCount;
//        }
//
//        //获取用户列表展示
//        List<User> userList = userService.getUserList(queryUserName, queryUserRole, currentpageNo, pagesize);
//      eq.setAttribute("userList",userList);  r
//
//        RoleServiceImpl roleService = new RoleServiceImpl();
//        List<Role> roleList = roleService.getRoleList();
//        req.setAttribute("roleList",roleList);
//        req.setAttribute("totalCount",totalCount);
//        req.setAttribute("currentpageNo",currentpageNo);
//        req.setAttribute("totalCount",totalCount);
//        req.setAttribute("queryUserName",queryUserName);
//        req.setAttribute("queryUserRole",queryUserRole);
//
//        //返回前端
//        req.getRequestDispatcher("userlist.jsp").forward(req,resp);
//
        //查询用户列表

        //从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
       // UserService userService = new UserServiceImpl();

        //第一次走页面一定是第一页,页面大小固定的
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;//5
        //当前页码
        int currentPageNo = 1;

        System.out.println("queryUserName servlet--------"+queryUserName);
        System.out.println("queryUserRole servlet--------"+queryUserRole);
        System.out.println("query pageIndex--------- > " + pageIndex);
        if(queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);//给查询赋值
        }

        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
                resp.sendRedirect("error.jsp");
            }
        }
        //总数量（表）
        int totalCount	= userService.getUserCount(queryUserName,queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();

        pages.setCurrentPageNo(currentPageNo);

        pages.setPageSize(pageSize);

        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }

        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize);
        req.setAttribute("userList", userList);
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        req.setAttribute("roleList", roleList);
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryUserRole);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);

        req.getRequestDispatcher("userlist.jsp").forward(req, resp);

    }

    //增加用户
    private void add(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        System.out.println("add()================");
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        UserService userService = new UserServiceImpl();
        if(userService.add(user)){
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else{
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }
    }

    //根据ID查找user
    private void getUserById(HttpServletRequest req, HttpServletResponse resp,String url)
            throws ServletException, IOException {
        String id = req.getParameter("uid");
        if(!StringUtils.isNullOrEmpty(id)){
            //调用后台方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserById(id);
            req.setAttribute("user", user);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }

     //根据ID删除user
    private void delUser(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String id = req.getParameter("uid");
        Integer delId = 0;
        try {
            delId = Integer.parseInt(id);
        } catch (Exception e) {
            // TODO: handle exception
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            UserService userService = new UserServiceImpl();
            if (userService.deleteUserById(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
    }

    //根据userCode查询出User
    private void userCodeExist(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //判断用户账号是否可用
        String userCode = req.getParameter("userCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            //userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        }else{
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode);
            if(null != user){
                resultMap.put("userCode","exist");
            }else{
                resultMap.put("userCode", "notexist");
            }
        }

        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        resp.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = resp.getWriter();
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }
        //根据条件查询列表
    private void getRoleList(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
    //修改用户信息
    private void modify(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        String userName = request.getParameter("userName");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        if(userService.modify(user)){
            response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
        }else{
            request.getRequestDispatcher("usermodify.jsp").forward(request, response);
        }

    }
}
